package com.jhxy.algorithm.merge;

import com.jhxy.algorithm.util.InputsForMerge;
import com.jhxy.algorithm.util.PrintTool;

import java.util.List;

/**
 * 合并两个有序数组暴力求解
 */
public class MergeViolence {

    /**
     * 暴力求解
     */
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        //1.首先要将num2数组中的元祖放到num1数组中(起始位置从m开始)
        for (int i = 0; i != n; i++) {
            nums1[m + i] = nums2[i];
        }
        //2.先定义num1中和num2中移动的角标i和j的起始位置
        int i = 0;
        int j = m;

        //然后定义i和j移动的次数
        int countI = 0;
        int countJ = 0;

        //3.开始进行对比num1[i]和num2[j]的值，决定是否需要移动
        while (countI < m && countJ < n) {
            //先将要对比的num1[i]和num2[j]的两个值存起来
            int left = nums1[i];
            int right = nums1[j];

            //如果num1[i] < nums2[j]的话，nums1中i后面的值不用移动,j向后移动
            if (left <= right) {
                i++;
                countI++;
            }

            else {
                //将nums1[i]向后移动
                for (int x = j; x > i ; x--) {
                    nums1[x] = nums1[x-1];
                }

                //数据移动之后，将right的值放到i上
                nums1[i] = right;
                i++;
                j++;
                countJ++;
            }
        }
    }


    public static void main(String[] args) {
        InputsForMerge inputs = new InputsForMerge("1,2,3,0,0,0;0;1", "3;0;1", "2,5,6;1;0", "3;1;0");
        PrintTool print = new PrintTool();
        MergeViolence ins = new MergeViolence();
        int i = 1;
        for (List<Object> input : inputs.inputs) {
            System.out.println("=================第" + (i++) + "组输入输出=================");
            print.printArray((int[]) input.get(0));
            System.out.println("");
            System.out.println("m:" + (int) input.get(1));
            print.printArray((int[]) input.get(2));
            System.out.println("");
            System.out.println("n:" + (int) input.get(3));
            int[] nums1 = (int[]) input.get(0);
            ins.merge(nums1, (int) input.get(1), (int[]) input.get(2), (int) input.get(3));
            print.printArray(nums1);
            System.out.println("");
        }
    }
}
